<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片试图-->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>

      <el-table :data="rolesList" border stripe>
        <!-- 展开列-->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdbottom', i1 == 0 ? 'bdtop' : '','vcenter']" v-for="(item1, i1) in scope.row.children" :key="item1.id">
              <!-- 以及权限-->
              <el-col :span="5">
                <el-tag closable @close="deleteRoleRightById(scope.row, item1.id)">{{item1.authName}}</el-tag><i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级权限-->
              <el-col :span="19">
                <el-row :class="[{'bdtop' : i2>0},'vcenter']" v-for="(item2, i2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="deleteRoleRightById(scope.row, item2.id)">{{item2.authName}}</el-tag><i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag type="warning" closable v-for="(item3, i3) in item2.children" :key="item3.id"
                      @close="deleteRoleRightById(scope.row, item3.id)">{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列-->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px" >
          <template slot-scope="scope" >
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="getRoleInfo(scope.row.id)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteRoleById(scope.row.id)">删除</el-button>
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色-->
    <el-dialog title="添加角色" :visible.sync="addDialogVisible" @close="addDialogClosed" width="50%">
      <!-- 内容主题区域-->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色-->
    <el-dialog title="修改角色信息" @close="editDialogClosed" :visible.sync="editUserDialogVisible" width="50%">
      <el-form :model="editForm" :rules="addFormRules" ref="editFormRef" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRuleInfo()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限-->
    <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%" @close="setRightDialogClosed">
      <!-- 树形控件 -->
      <el-tree ref="rightsRef" :data="rightsList" :props="treeProps" show-checkbox default-expand-all node-key="id" :default-checked-keys="defKeys"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRight()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        //所有角色的列表数据
        rolesList : [],
        //控制添加角色对话框的显示与隐藏
        addDialogVisible: false,
        //添加角色的表单数据
        addForm: {
          roleName: "",
          roleDesc: ''
        },
        //添加表单的验证规则对象
        addFormRules: {
          roleName: [{
              required: true,
              message: "请输入角色名称",
              trigger: 'blur'
            }
          ],
          roleDesc: [{
              required: true,
              message: "请输入角色描述",
              trigger: 'blur'
            }
          ]
        },

        //编辑角色信息对话框显示与吟唱
        editUserDialogVisible: false,
        //编辑角色信息
        editForm: {},
        //控制分配权限对话框的显示于隐藏
        setRightDialogVisible: false,
        //所有的权限
        rightsList:[],
        //
        treeProps:{
          children: 'children',
          label: 'authName'
        },
        //默认选中的
        defKeys:[],
        //当前分配权限的角色id
        roleId:0
      }
    },
    created() {
      this.getRolesList();
    },
    methods:{
      //获取角色列表数据
      async getRolesList() {
        const {data:res} = await this.$http.get("roles");
        if (res.meta.status !== 200) {
          return this.$message.error("获取角色列表数据失败")
        }
        this.rolesList = res.data;
        console.log(res)
      },
      //添加角色
      async addRoles() {
        const {data: res} = await this.$http.post('roles', this.addForm);
        console.log(res)
        if (res.meta.status !== 201) {
          return this.$message.error("添加角色失败！")
        }
        this.$message.success("添加角色成功！")
        this.addDialogVisible = false;
        this.getRolesList();
      },
      //添加角色对话框隐藏监听事件
      addDialogClosed() {
        this.$refs.addFormRef.resetFields();
      },

      //编辑角色对话框隐藏监听事件
      editDialogClosed() {
        this.$refs.editFormRef.resetFields();
      },
      //获取角色信息
      async getRoleInfo(id) {
        const {data : res} = await this.$http.get('roles/'+id);
        console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error("获取角色信息失败！")
        }
        this.editForm = res.data;
        this.editUserDialogVisible = true;
      },

      //修改角色信息
      editRuleInfo() {
        this.$refs.editFormRef.validate(async valid => {
          if (!valid) {
            return
          }
          const {data, res} = await this.$http.put('roles/' + this.editForm.roleId, {roleName:this.editForm.roleName, roleDesc:this.editForm.roleDesc});
          console.log(res)
          if (res.meta.status !== 200) {
            return this.$message.error("修改角色失败！")
          }
          this.$message.success("修改角色成功！")
          this.editUserDialogVisible = false;
          this.getRolesList();
        })
      },
      //根据角色id删除角色
      async deleteRoleById(id) {
        const confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)

        console.log(confirmResult);
        if (confirmResult !== 'confirm') {
          return this.$message.info("取消了删除操作")
        }
        console.log("确认删除此角色")
        const {data : res} = await this.$http.delete("roles/" + id);
        if (res.meta.status !== 200) {
          return this.$message.error("删除角色失败")
        }
        this.$message.success("删除角色成功！")
        this.getRolesList();
      },
      //删除角色的权限
      async deleteRoleRightById(role , id) {
        const confirmResult = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)

        console.log(confirmResult);
        if (confirmResult !== 'confirm') {
          return this.$message.info("取消了删除操作")
        }
        console.log("确认删除此权限")
        const {data : res} = await this.$http.delete(`roles/${role.id}/rights/${id}`);
        if (res.meta.status !== 200) {
          return this.$message.error("删除权限失败")
        }
        this.$message.success("删除权限成功！")
        role.children = res.data;
      },

      //显示添加权限对话框
      async showSetRightDialog(role) {
        this.roleId = role.id;
        const {data:res} = await this.$http.get("rights/tree");
        console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error("获取权限列表失败！")
        }
        this.rightsList = res.data;
        //遍历获取权限第三级的所有id
        this.getNodeKeys(role, this.defKeys)
        console.log(this.defKeys)
        this.setRightDialogVisible = true;

      },
       //递归获取第三级节点的id
      getNodeKeys(node, arr) {
        //如果当前节点不含有 children 则当前节点是第三级节点
        if (!node.children) {
          return arr.push(node.id)
        }
        //不是第三级节点，则遍历其所有子节点
        node.children.forEach(item => this.getNodeKeys(item, arr));
      },
      //监听分配权限对话框的关闭事件
      setRightDialogClosed() {
        this.defKeys = []
      },
      //分配权限请求
      async allotRight() {
        const keys = [
          ...this.$refs.rightsRef.getCheckedKeys(),
          ...this.$refs.rightsRef.getHalfCheckedKeys()
        ]
        const parKeys = keys.join(',')
        const {data : res} = await this.$http.post(`roles/${this.roleId}/rights`, {rids:parKeys})
        console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error("分配权限失败！")
        }
        this.$message.success("分配权限成功！")
        this.setRightDialogVisible = false;
        this.getRolesList()
      }
    }
  }
</script>

<style lang="less" scoped>
  .el-tag {
    margin: 7px;
  }
  .bdtop {
    border-top: 1px solid #EEEEEE;
  }
  .bdbottom {
    border-bottom: 1px solid #EEEEEE;
  }
  .vcenter {
    display: flex;
    align-items: center;
  }
</style>
